require('es6-promise').polyfill()

import Vue from 'vue'
import { sync } from 'vuex-router-sync'
import VueProgressBar from 'vue-progressbar'
import VueLazyload from 'vue-lazyload'
import { Loading } from 'element-ui'
import axios from 'axios'
import env from './config/common'

const localStorage = require('store')

Vue.use(Loading)

Vue.use(VueProgressBar, {
  color: '#f7ba2a',
  failedColor: 'red',
  height: '2px'
})

Vue.use(VueLazyload, {
  try: 3 // default 1
})

import App from './components/App'
import router from './router'
import store from './store'

const commit = store.commit || store.dispatch
const user = localStorage.get('user')

if (user) {
  commit('UPDATE_USER', user)
  axios.get(
    env.CRM_API_HOST + '/users/' + user.token
  ).then((response) => {
    if (response.data.errcode === 0) {
      commit('UPDATE_USER', user)
    } else {
      commit('UPDATE_USER', false)
      localStorage.remove('user')
    }
    // 没有登录，就去登录
    router.beforeEach(function (to, from, next) {
      if (to.name !== 'login' && to.name !== 'home' && !store.state.auth.user) {
        // router.push({ name: 'login' })
        window.location.href = 'user/login'
      }
      next()
    })
  }).catch((err) => {
    console.log(err)
  })
} else {
  router.beforeEach(function (to, from, next) {
    if (to.name !== 'login' && to.name !== 'home' && !store.state.auth.user) {
      router.push({ name: 'login' })
    } else {
      next()
    }
  })
}

sync(store, router)

const app = new Vue({
  router,
  store,
  ...App
})

export { app, router, store }
